/**
 * 定义TodoList类：
 * 实现增加，删除，切换等状态
 */

import { todoView } from "./template"
import { addTodo, changeCompleted, removeTodo } from "./todoEvent"
import { ITodo } from "./typings"

class TodoList {
  //单例模式
  private static instance: TodoList
  private oTodoList: HTMLElement

  constructor(oTodoList: HTMLElement) {
    this.oTodoList = oTodoList
  }
  //创建单例的方法
  public static createInstance(oTodoList: HTMLElement) {
    if(!TodoList.instance) {
      TodoList.instance = new TodoList(oTodoList)
    }
    return TodoList.instance
  }
  /**
   * 增加的方法
   * @param todo
   * 具体步骤：创建外层容器，添加类，调用view视图层代码片段追加到创建的容器，再把容器追加到类初始化的容器中 
   */
  @addTodo
  public addItem(todo: ITodo) {
    const oItem: HTMLElement = document.createElement('div')
    oItem.className = 'todo-item'
    oItem.innerHTML = todoView(todo)
    this.oTodoList.appendChild(oItem)
  }

  @removeTodo
  public removeItem(id: number) {
    const oItems: HTMLCollection = document.getElementsByClassName('todo-item')

    Array.from(oItems).map((oItem) => {
      const _id = parseInt(oItem.querySelector('button').dataset.id)
      if(id === _id) {
        oItem.remove()
      }
    })
    
  }

  @changeCompleted
  public toggleCompleted(id: number, completed?:boolean) {
    const oItems: HTMLCollection = document.getElementsByClassName('todo-item')
    Array.from(oItems).map(oItem => {
      const _id = parseInt(oItem.querySelector('input').dataset.id)
      // const _checked = oItem.querySelector('input').checked
      if(_id === id) {
        const oContent: HTMLElement = oItem.querySelector('span')
        oContent.style.textDecoration = completed ? 'line-through' : 'none'
      }
    })
  }
}

export default TodoList